/**
 * datebox wrap My97DatePicker - jQuery xui
 *
 * Licensed under the Apache v2
 *
 * Copyright 2015 xjb [ beymy.en@gmail.com ]
 *
 */
(function($) {

    function init(target) {
        var state = $.data(target, 'datebox');
        var opts = state.options;

        $(target).addClass('Wdate datebox-f').validatebox($.extend({
            required: opts.required,
            validType: opts.validType,
            novalidate: opts.novalidate
        }, opts.validateOptions));
    }

    function bindEvents(target) {
        var state = $.data(target, 'datebox');
        var opts = state.options;
		var t = $(target);
		
        //先取消绑定事件
        t.unbind('.datebox');

        if (!opts.disabled) {
			t.bind(opts.showEvent+'.datebox', function() {
				window.WdatePicker(opts.datePickerOptions);
			});
        }
    }

    function setDisabled(target, disabled) {
        var state = $.data(target, 'datebox');
        var opts = state.options;
		var t = $(target);
		
        if (disabled) {
            opts.disabled = true;
            t.attr('readonly', 'readonly');
        } else {
            opts.disabled = false;
            t.removeAttr('readonly');
        }
    }

    $.fn.datebox = function(options, param) {
        if (typeof options == 'string') {
            return $.fn.datebox.methods[options](this, param);
        }

        options = options || {};
        return this.each(function() {
            var state = $.data(this, 'datebox');
            var opts;
            if (state) {
                opts = $.extend(state.options, options);
            } else {
                opts = $.extend({}, $.fn.datebox.defaults, $.fn.datebox.parseOptions(this), options);
                $.data(this, 'datebox', {
                    options: opts
                });

                init(this);
            }

            setDisabled(this, opts.disabled);
            //setSize(this);
            bindEvents(this);
        });
    };


    $.fn.datebox.methods = {
        options: function(jq) {
            return $.data(jq[0], 'datebox').options;
        },
        disable: function(jq) {
            return jq.each(function() {
                setDisabled(this, true);
                bindEvents(this);
            });
        },
        enable: function(jq) {
            return jq.each(function() {
                setDisabled(this, false);
                bindEvents(this);
            });
        }
    };

    $.fn.datebox.parseOptions = function(target) {
        return $.extend({}, $.parser.parseOptions(target));
    };

    $.fn.datebox.defaults = {
    	showEvent: 'focus',
        validateOptions: {
            handler: {
                tip: function(target) {
                    //返回jquery对象
                    return $(target);
                }
            }
        },
        datePickerOptions: {
        }
    };
})(jQuery);